#!/usr/bin/python
# -*- coding: utf-8 -*-

import cjcx
import socket
import re
import os.path

print "Content-Type: text/html"
print
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(("121.101.217.125",80))
get_str = """GET /cronlist.php?cron=ts HTTP/1.1
Connetion: keep-alive
HOST: scutter.rwnest.com

"""
sock.sendall(get_str)
head = ""
chunk = ""
body = ""
while True:
    t = sock.recv(1024)
    if "\r\n\r\n" in t:
        loc = t.find("\r\n\r\n")
        head += t[:loc]
        chunk = t[loc+4:]
        break
    else:
        head += t

while True:
    loc = chunk.find("\r\n")
    if loc==-1: chunk+=sock.recv(1024)
    chunk_len = int(chunk[:loc],16)
    if chunk_len==0:
        break
    chunk = chunk[loc+2:]
    while len(chunk)<chunk_len:
        chunk += sock.recv(1024)
    body += chunk[:chunk_len]
    chunk = chunk[chunk_len+2:]
sock.close()
body = body.strip()
users = body.split()
import cPickle
from sets import Set
for user in users:
    userid, passwd = user.split(":")
    keys = []
    marks = cjcx.query(userid, passwd)
    new_keys = []
    if os.path.exists("data/"+userid):
        fr = open("data/"+userid, "r")
        keys = cPickle.load(fr)
        fr.close()  
        new_keys = list(Set(marks.keys()) - Set(keys))
        
    content = ""
    for new_key in new_keys:
        content += "%s:%s=>" % (marks[new_key][0], marks[new_key][1])
    if content:
        content = content[:-2]
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.connect(("121.101.217.125",80))
        get_str = """GET /mailler.php?jwuser=%s&cron=ts&content=%s HTTP/1.1
Connetion: keep-alive
HOST: scutter.rwnest.com

""" % (userid, content)
        sock.sendall(get_str)
        print "send"
        sock.close()
    fw = open("data/"+userid, "w")
    cPickle.dump(marks.keys(), fw)
    fw.close()
 
